﻿using Basic.FlowModel.DB;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.FlowApp.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Basic.FlowDAL.lmpl
{
    internal class FlowAppDAL : BasicDAL<DBFlowApp, long>, IFlowAppDAL
    {
        public FlowAppDAL ( IRepository<DBFlowApp> basicDAL ) : base(basicDAL, "app")
        {
        }
        public void SetSettleFormId ( DBFlowApp app, long? formId )
        {
            if ( app.SettleFormId.HasValue )
            {
                ISqlQueue<DBFlowApp> queue = this._BasicDAL.BeginQueue();
                queue.UpdateOneColumn(a => a.SettleFormId == formId, a => a.Id == app.Id);
                queue.DeleteBy<DBFlowAppFormRelation>(c => c.AppId == app.Id);
                _ = queue.Submit();
            }
            else if ( !this._BasicDAL.Update(a => a.SettleFormId == formId, a => a.Id == app.Id) )
            {
                throw new ErrorException("flow.app.update.fail");
            }
        }
        public long Add ( FlowAppSet data )
        {
            DBFlowApp db = new DBFlowApp
            {
                AppName = data.AppName,
                Status = FlowAppStatus.起草,
                AppClassify = data.AppClassify,
                AppType = data.AppType,
                AppShow = data.AppShow,
                FlowId = data.FlowId,
                FlowVer = data.FlowVer,
                TitleTemplate = data.TitleTemplate,
                Id = IdentityHelper.CreateId()
            };
            base._BasicDAL.Insert(db);
            return db.Id;
        }
        public void Enable ( DBFlowApp app )
        {
            app.AppTime = DateTime.Now;
            app.Status = FlowAppStatus.启用;
            if ( !base._BasicDAL.Update(app, new string[] {
                "Status",
                "AppTime"
            }) )
            {
                throw new ErrorException("flow.app.update.fail");
            }
        }

        public DBFlowApp[] Query ( FlowAppQuery query, IBasicPage paging, out int count )
        {
            paging.InitOrderBy("Id", true);
            return this._BasicDAL.Query(query.ToWhere(), paging, out count);
        }

        public void Stop ( DBFlowApp app )
        {
            app.AppTime = null;
            app.Status = FlowAppStatus.停用;
            if ( !base._BasicDAL.Update(app, new string[] {
                "Status",
                "AppTime"
            }) )
            {
                throw new ErrorException("flow.app.update.fail");
            }
        }
    }
}
